package com.gp.common.utils;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gp.exception.CustomException;

/**
 * Author: D.Yang Email: koyangslash@gmail.com Date: 16/8/31 Time: 下午5:42 Describe: String工具类
 */
public class StringUtil {

  // 定义下划线
  private static final char UNDERLINE = '_';

  /**
   * String为空判断
   *
   * @param str 需判断字符串
   * @return true:为空 false:不为空
   */
  public static boolean isEmpty(String str) {
    return str == null || "".equals(str.trim());
  }

  /**
   * String不为空判断
   *
   * @param str 需判断字符串
   * @return true:不为空 false:为空
   */
  public static boolean isNotEmpty(String str) {
    return !isEmpty(str);
  }

  /**
   * 驼峰转下划线工具
   *
   * @param param 需要转换的字符串
   * @return 转换好的字符串
   */
  public static String camelToUnderline(String param) {
    if (isNotEmpty(param)) {
      int len = param.length();
      StringBuilder sb = new StringBuilder(len);

      for (int i = 0; i < len; ++i) {
        char c = param.charAt(i);
        if (Character.isUpperCase(c)) {
          sb.append(UNDERLINE);
          sb.append(Character.toLowerCase(c));
        } else {
          sb.append(c);
        }
      }

      return sb.toString();
    } else {
      return "";
    }
  }

  /**
   * 下划线转驼峰工具
   *
   * @param param 需要转换的字符串
   * @return 转换好的字符串
   */
  public static String underlineToCamel(String param) {
    if (isNotEmpty(param)) {
      int len = param.length();
      StringBuilder sb = new StringBuilder(len);

      for (int i = 0; i < len; ++i) {
        char c = param.charAt(i);
        if (c == 95) {
          ++i;
          if (i < len) {
            sb.append(Character.toUpperCase(param.charAt(i)));
          }
        } else {
          sb.append(c);
        }
      }

      return sb.toString();
    } else {
      return "";
    }
  }


  public static String converStr(String str) throws CustomException {
    try {
      return new String(str.getBytes("ISO-8859-1"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      throw new CustomException("转码错误");
    }
  }

  /**
   * 在字符串两周添加''
   *
   * @param param 字符串
   * @return 处理后的字符串
   */
  public static String addSingleQuotes(String param) {
    return "\'" + param + "\'";
  }

  /**
   * 获取时间字符串.传入空，默认为当前的时间
   *
   * @param param 字符串
   * @return 处理后的字符串
   */
  public static String obtinDateStr(Date date) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date newDate = date == null ? new Date() : date;
    return df.format(newDate);
  }

  /**
   * 获取时间前一周的时间
   *
   * @param param 字符串
   * @return 处理后的字符串
   */
  public static String obtinDateStrBeforeWeek() {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar=Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.DAY_OF_MONTH, -7);
    return df.format(calendar.getTime());
  }
  
  /**
   * 获取时间当前
   *
   * @param param 字符串
   * @return 处理后的字符串
   */
  public static String obtinDateStrCurrentTime() {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar=Calendar.getInstance();
    calendar.setTime(new Date());
    return df.format(calendar.getTime());
  }
  public static void main(String[] args) {
    System.out.println(StringUtil.obtinDateStrBeforeWeek());
  }
  
  /**
   * 拼装 where语句 like子句
   * 
   * @param ew 条件包装类
   * @param condition 需要封装的条件
   * @return 拼接完成以后的包装类
   */
  public static Wrapper addWhereLikeCondition(Wrapper ew, Map condition) {
    Set<Map.Entry<String, Object>> entry = condition.entrySet();
    Iterator<Entry<String, Object>> iterator = entry.iterator();
    while (iterator.hasNext()) {
      Entry<String, Object> next = iterator.next();
      ew.like(next.getKey(), next.getValue().toString());
    }
    return ew;
  }

  /**
   * 将用 "," 隔开的字符串分割成Long数组
   * 
   * @param str 需要分割的字符串
   * @return List<Long>
   */
  public static List<Long> StrToLongList(String str) {
    List<Long> list = new ArrayList<Long>();
    if (!isEmpty(str)) {
      String[] strings = str.split(",");
      for (String s : strings) {
        list.add(Long.parseLong(s));
      }
    }
    return list;
  }

  /**
   * 校验日期
   * 
   * @param starttime
   * @param endtime
   */
  public static boolean validDate(String starttime, String endtime) {
    starttime = StringUtils.hasText(starttime) ? starttime.trim() : "2018-01-01";
    endtime = StringUtils.hasText(endtime) ? endtime.trim() : "2999-01-01";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    boolean flag = false;
    try {
      df.parse(starttime);
      df.parse(endtime);
      flag = true;
    } catch (Exception e) {
    }
    return flag;
  }

  /**
   * 自动生成32位的UUid，对应数据库的主键id进行插入用。
   * 
   * @return
   */
  public static String getUUID() {
    return UUID.randomUUID().toString().replace("-", "");
  }

  /**
   * 判断一个访问连接是否是静态资源
   * 
   * @param requestURI
   * @return
   */
  public static boolean isAccessStaticResource(String requestURI) {

    return requestURI.endsWith(".js") || requestURI.endsWith(".css") || requestURI.endsWith(".eot")
        || requestURI.endsWith(".svg") || requestURI.endsWith(".img") || requestURI.endsWith(".jpg")
        || requestURI.endsWith(".JPG") || requestURI.endsWith(".woff")
        || requestURI.endsWith(".woff2") || requestURI.endsWith(".ttf")
        || requestURI.endsWith(".otf") || requestURI.endsWith(".png") || requestURI.endsWith(".gif")
        || requestURI.endsWith(".woff") || requestURI.endsWith(".woff")
        || requestURI.endsWith(".woff")|| requestURI.endsWith(".webp");
  }
}
